package ute.tlcn.struts2hibernate.dao;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;

import ute.tlcn.struts2hibernate.javabean.Item;
import ute.tlcn.struts2hibernate.javabean.Order;

public class ItemDAOImpl implements ItemDAO {

	private Session session;
	
	public ItemDAOImpl() {
		session = HibernateUtil.getSesisonFactory().getCurrentSession();
	}
	
	@Override
	public void insert(Item item) throws Exception {
		session.persist(item);
	}

	@Override
	public void delete(Integer itemId) throws Exception {
		session.delete(session.load(Item.class, itemId));
	}

	@Override
	public void update(Item item) throws Exception {
		session.update(item);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Item> list() throws Exception {
		return session.createQuery("from Item").list();
	}

	@Override
	public Item findById(Integer itemId) throws Exception {
		//return (Item) session.createQuery("from Item where id = :id").setInteger("id", itemId).uniqueResult();
		return (Item) session.get(Item.class, itemId);
	}
	
	
	public static void main(String[] args) throws Exception {
		HibernateUtil.getSesisonFactory().getCurrentSession().beginTransaction();
		
		ItemDAO dao = new ItemDAOImpl();
		Set<Order> orders = null;
		
		List<Item> items = dao.list();
		for(Item i : items) {
			System.out.println(i.getName());
			orders = i.getOrders();
			//System.out.println(orders.size());
			for(Order o : orders) {
				System.out.println(o.getDate());
			}
		}
		
		
		/*Item i = dao.findById(7);
		System.out.println(i.getName());
		List<Order> orders = (List<Order>) i.getOrders();
		for(Order o : orders) {
			System.out.println(o.getAmount());
		}*/
		
		HibernateUtil.getSesisonFactory().getCurrentSession().getTransaction().commit();
		HibernateUtil.close();
	}
}
